{% extends "layout/manage.html" %}
{% load static %}

{% block title %}
    文件
{% endblock %}

{% block css %}
    <style>
        .panel-default .panel-heading {
            display: flex;
            flex-direction: row;
            justify-content: space-between;
        }

        .panel-default .panel-heading a {
            text-decoration: none;
        }

        .panel-default .panel-heading span {
            padding: 0 5px;
        }


        .file-name {
            color: rgba(47, 33, 33, 0.43);
        }

        .panel-default > .panel-heading .function .upload {
            overflow: hidden;
        }

        .panel-default > .panel-heading .function .upload input {
            opacity: 0;
            position: absolute;
            top: 0;
            bottom: 0;
            width: 76px;
            left: -2px;
            overflow: hidden;
        }

        .upload-progress {
            position: fixed;
            right: 2px;
            bottom: 2px;
            width: 400px;
        }

        .upload-progress .progress-error {
            color: red;
        }
    </style>
{% endblock %}

{% block content %}
    <div class="container-fluid">
        <div class="panel panel-default">
            <div class="panel-heading">
                <div>
                    {% if url_list %}
                        <a href="{% url "file" project_id=request.tartec.project.id %}"><i class="fa fa-folder"
                                                                                           aria-hidden="true"></i>
                            文件库</a>
                        {% for item in url_list %}
                            <i class="fa fa-angle-right" aria-hidden="true"></i>
                            <a href="{% url "file" project_id=request.tartec.project.id %}?folder={{ item.id }}"><i
                                    class="fa fa-folder"
                                    aria-hidden="true"></i>
                                {{ item.title }}</a>
                        {% endfor %}
                    {% else %}
                        <a href="{% url "file" project_id=request.tartec.project.id %}"><i class="fa fa-folder"
                                                                                           aria-hidden="true"></i>
                            文件库</a>
                    {% endif %}
                </div>
                <div class="function">
                    <div class="btn btn-info btn-xs upload" style="position: relative">
                        <div><i class="fa fa-upload" aria-hidden="true"></i> 上传文件</div>
                        <input type="file" multiple name="uploadFile" id="uploadFile">
                    </div>
                    <a type="button" class="btn btn-primary" data-toggle="modal" data-target="#addModal"
                       data-whatever="新建文件夹"><i class="fa fa-plus-circle" aria-hidden="true"></i>
                        新建文件夹
                    </a>
                </div>
            </div>
            <div class="panel-body">
                <table class="table">
                    <thead>
                    <tr>
                        <th>文件名</th>
                        <th>文件大小(KB)</th>
                        <th>修改者</th>
                        <th>修改时间</th>
                        <th>操 作</th>
                    </tr>
                    </thead>
                    <tbody id="fileFolderList">
                    {% for item in file_dict.folder %}
                        <tr>
                            <td><a href="{% url "file" project_id=request.tartec.project.id %}?folder={{ item.id }}"
                                   class="file-name"><i
                                    class="fa fa-folder"
                                    aria-hidden="true"></i> {{ item.item.title }}
                            </a>
                            </td>
                            <td>——</td>
                            <td>{{ item.item.revise.username }}</td>
                            <td>{{ item.item.update_date }}</td>
                            <td>
                                <a type="button" class="btn btn-primary btn-xs"
                                   data-toggle="modal"
                                   data-target="#addModal"
                                   data-whatever="修改文件夹"
                                   data-name="{{ item.item.title }}"
                                   data-fid="{{ item.item.id }}">
                                    <i class="fa fa-edit" aria-hidden="true"></i>
                                </a>
                                <a type="button" class="btn btn-danger btn-xs"
                                   data-toggle="modal"
                                   data-target="#delModal"
                                   data-fid="{{ item.item.id }}">
                                    <i class="fa fa-trash" aria-hidden="true"></i>
                                </a>
                            </td>
                        </tr>
                    {% endfor %}

                    {% for item in file_dict.file %}
                        <tr>
                            <td><i class="fa fa-file" aria-hidden="true"></i> {{ item.item.title }}
                            </td>
                            <td>{{ item.size }}</td>
                            <td>{{ item.item.revise.username }}</td>
                            <td>{{ item.item.update_date }}</td>
                            <td>
                                <a class="btn btn-default btn-xs download"
                                   id="download"
                                   href="{% url "download_file" project_id=request.tartec.project.id file_id=item.item.id %}"
                                >
                                    <i class="fa fa-cloud-download" aria-hidden="true"></i>
                                </a>
                                <a type="button" class="btn btn-danger btn-xs"
                                   data-toggle="modal"
                                   data-target="#delModal"
                                   data-fid="{{ item.item.id }}">
                                    <i class="fa fa-trash" aria-hidden="true"></i>
                                </a>
                            </td>
                        </tr>
                    {% endfor %}

                    </tbody>
                </table>
            </div>
        </div>
    </div>


    <!-- Modal -->
    <div class="modal fade" id="addModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                            aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title" id="exampleModalLabel"></h4>
                </div>
                <div class="modal-body">
                    <form action="" id="form">
                        {% csrf_token %}
                        <input class="hide" type="text" name="fid" id="fid">
                        {% for item in form %}
                            <div class="form-group">
                                <label for="{{ item.id_for_label }}">{{ item.label }}</label>
                                {{ item }}
                                <span class="error_msg">{{ item.errors.0 }}</span>
                            </div>
                        {% endfor %}
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                    <button type="button" id="btnFormSubmit" class="btn btn-primary">提 交</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 警告框 -->
    <div class="modal fade" id="delModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <div class="alert alert-danger alert-dismissible fade in" role="alert">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                        aria-hidden="true">×</span></button>
                <h4>是否要确定删除？</h4>
                <p style="padding-top: 20px;padding-bottom: 20px;">
                    文件夹中包含的所有的文件都会被删除。
                </p>
                <p style="text-align: right;">
                    <a class="btn btn-default btn-sm" data-dismiss="modal" aria-label="Close">取 消</a>
                    <button id="delete_file" type="button" class="btn btn-danger btn-sm">确 定</button>
                </p>
            </div>
        </div>
    </div>
    <!-- 升级vip 模态框 -->
    <div class="modal fade" id="warning" tabindex="-1" role="dialog">
        <div class="modal-dialog" role="document">
            <div class="alert alert-warning alert-dismissible fade in" role="alert">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                            aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title">警告！</h4>
                </div>
                <div class="modal-body">
                    <p>超出容量限制，请升级会员</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关 闭</button>
                    <button type="button" class="btn btn-primary">升级会员</button>
                </div>
            </div><!-- /.modal-content -->
        </div><!-- /.modal-dialog -->
    </div><!-- /.modal -->
    <!-- 上传模态框 -->
    <div id="uploadProgress" class="upload-progress hide">
        <div class="panel panel-primary">
            <div class="panel-heading">
                <i class="fa fa-cloud-upload" aria-hidden="true"></i> 上传进度
            </div>

            <table class="table">
                <tbody id="progressList">

                </tbody>
            </table>
        </div>
    </div>
    <!-- 进度条模板 -->
    <div class="hide">
        <table id="progressTemplate">
            <tr>
                <td>
                    <div class="name"></div>
                    <div class="progress">
                        <div class="progress-bar progress-bar-success progress-bar-striped" role="progressbar"
                             aria-valuenow="60" aria-valuemin="0"
                             aria-valuemax="100"
                             style="width: 0;">
                            0%
                        </div>
                    </div>
                    <div class="progress-error"></div>
                </td>
            </tr>
        </table>
    </div>
    <!-- 文件列表模板 -->
    <div class="hide">
        <table id="rowTpl">
            <tr>
                <td>
                    <i class="fa fa-file" aria-hidden="true"></i>
                    <span class="name"></span>
                </td>
                <td class="file_size"></td>
                <td class="username"></td>
                <td class="datetime"></td>
                <td>
                    <a class="btn btn-default btn-xs download"

                    >
                        <i class="fa fa-cloud-download" aria-hidden="true"></i>
                    </a>
                    <a type="button" class="btn btn-danger btn-xs delete"
                       data-target="#delModal"
                       data-toggle="modal">
                        <i class="fa fa-trash" aria-hidden="true"></i>
                    </a>
                </td>
            </tr>
        </table>
    </div>
{% endblock %}

{% block js %}
    <script src="{% static "js/cos-js-sdk-v5.min.js" %}"></script>
    <script src="{% static "plugin/cos-js-sdk-v5/tmp/Source/cos-js-sdk-v5-1.5.0/dist/cos-js-sdk-v5.min.js" %}"></script>
    <script>
        var DEFAULT_URL = "{% url "file" project_id=request.tartec.project.id %}"
        var DELETE_URL = "{% url "del_file" project_id=request.tartec.project.id %}"
        var COS_CREDENTIAL_URL = "{% url "cos_credential" project_id=request.tartec.project.id %}"
        $(() => {

            deleteFile()
            initModel()
            bindUploadFile()
            bindSubmit()
        })

        function initModel() {
            $('#addModal').on('show.bs.modal', function (event) {
                var button = $(event.relatedTarget) // Button that triggered the modal
                var recipient = button.data('whatever') // Extract info from data-* attributes
                var name = button.data('name') // Extract info from data-* attributes
                var fid = button.data('fid') // Extract info from data-* attributes
                // If necessary, you could initiate an AJAX request here (and then do the updating in a callback).
                // Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead.
                var modal = $(this)
                modal.find('.modal-title').text(recipient)
                if (fid) {
                    // 编辑
                    $("#id_title").val(name)
                    $("#fid").val(fid)
                } else {
                    // 新建
                    $(".error_msg").empty()
                    $("#form")[0].reset()
                }
            })

            $('#delModal').on('show.bs.modal', function (event) {
                var button = $(event.relatedTarget) // Button that triggered the modal
                var fid = button.data('fid') // Extract info from data-* attributes
                $("#delete_file").attr("fid", fid)
            })
        }

        function deleteFile() {
            $('#delete_file').click(function () {
                // 获取要删除那行ID
                $.ajax({
                    url: DELETE_URL,
                    type: "GET",
                    data: {fid: $(this).attr('fid')},
                    success: function (res) {
                        if (res.status) {
                            location.href = location.href;
                        }
                    }
                })
            })

        }

        function bindUploadFile() {
            $("#uploadFile").change(function () {
                // 用来存储上传文件的名字以及大小
                var fileList = []
                var files = $(this)[0].files
                $.each(files, function (index, fileObject) {
                    fileName = fileObject.name
                    fileSize = fileObject.size
                    fileList.push({"name": fileName, "size": fileSize})
                })
                var cos_credential = new COS({
                    getAuthorization: function (options, callback) {
                        // 想django后台发送请求，获取临时凭证
                        $.post(COS_CREDENTIAL_URL,
                            JSON.stringify(fileList), // 复杂数据需要转换成JSON 格式发送到django 后端
                            function (res) {
                                console.log(res)
                                if (res.status) {
                                    var credentials = res.data && res.data.credentials;
                                    callback({
                                        TmpSecretId: credentials.tmpSecretId,
                                        TmpSecretKey: credentials.tmpSecretKey,
                                        XCosSecurityToken: credentials.sessionToken,
                                        StartTime: res.data.startTime,
                                        ExpiredTime: res.data.expiredTime,
                                    });
                                } else {
                                    $('#warning').modal("show")
                                    var model = $(this)
                                    $(".modal-body p").text(res.data.error)
                                }
                            });
                    }
                })
                $.each(files, function (index, fileObject) {
                    var fileName = fileObject.name
                    var fileSize = fileObject.size
                    var key = (new Date()).getTime() + "_" + fileName
                    var tr = $("#progressTemplate").find("tr").clone()
                    tr.find(".name").text(fileName)
                    $("#progressList").append(tr)
                    // 上传文件
                    cos_credential.putObject({
                        Bucket: "{{ request.tartec.project.bucket }}",
                        Region: "{{ request.tartec.project.region }}",
                        Key: key,
                        Body: fileObject,
                        onProgress: function (progressData) { // 上传的进度
                            $("#uploadProgress").removeClass("hide") // 进度条显示出来
                            var percent = progressData.percent * 100 + "%"
                            tr.find(".progress-bar").text(percent)
                            tr.find(".progress-bar").css("width", percent)
                        }
                    }, function (err, data) { // 本次上传文件的情况
                        console.log(err || data);
                        if (data && data.statusCode === 200) {
                            // 需要将本次上传的文件提交到后台
                            // 本次文件上传成功
                            $.post("{% url "upload_file" project_id=request.tartec.project.id %}",
                                {
                                    "title": fileName,
                                    "size": fileSize,
                                    "key": key,
                                    "parent_id": "{{ folder }}",
                                    "file_path": data.Location,
                                    "etag": data.ETag
                                },
                                function (res) {
                                    if (res.status) {
                                        var newTr = $("#rowTpl").find("tr").clone()
                                        newTr.find(".name").text(res.data.title)
                                        newTr.find(".username").text(res.data.username)
                                        newTr.find(".file_size").text(res.data.file_size)
                                        newTr.find(".datetime").text(res.data.update)
                                        newTr.find(".delete").attr("data-fid", res.data.id)
                                        newTr.find(".download").attr("href", res.data.download_url)
                                        $("#fileFolderList").append(newTr)
                                        // 删除记录
                                        tr.remove()
                                    } else {

                                    }
                                })
                        } else {
                            tr.find("progress-error").text("上传失败")
                        }
                    });
                })
                $("#uploadProgress").addClass("hide") // 进度条隐藏
            })
        }

        function bindSubmit() {
            // 点击事件，通过Ajax发送POST请求
            $("#btnFormSubmit").click(() => {
                $.ajax({
                    url: DEFAULT_URL, // 请求的URL，用于提交表单数据
                    type: "POST", // 请求方法为POST
                    data: $("#form").serialize(), // 提交的表单数据，通过序列化获取
                    dataType: "JSON", // 返回的数据类型为JSON
                    success: function (res) { // 请求成功后的回调函数
                        console.log(res) // 打印返回的数据
                        if (res.status) { // 如果返回的状态为true
                            location.href = location.href // 重新加载当前页面
                            // location.reload() 两个都是刷新一下页面，可以把创建的项目显示到页面
                        } else { // 如果返回的状态为false
                            $.each(res.error, function (key, value) { // 遍历错误信息
                                $("#id_" + key).next().text(value[0]) // 将错误信息展示在对应字段的下一个兄弟元素上
                            })
                        }
                    }
                })
            })
        }
    </script>
{% endblock %}

